package others;

import java.util.concurrent.Phaser;

/**
 * phaser是作为阶段性控制，每个阶段完成，才能继续往下面走
 */
public class PaserTest {
    public static final MarryPhaser phaser = new MarryPhaser();

    public static void main(String[] args) {
        phaser.bulkRegister(7);

        for (int i = 0; i < 5; i++) {
            new Thread(new Person("客人"+i)).start();
        }
        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();
    }

    static class Person implements Runnable {

        private String name;

        public Person(String name) {
            this.name = name;
        }

        private void arrive() {
            System.out.printf("%s 已经到了%n", name);
            //等待
            phaser.arriveAndAwaitAdvance();
            System.out.printf("%s arrive end%n", name);
        }

        private void eat() {
            System.out.printf("%s 吃完%n", name);
            //等待
            phaser.arriveAndAwaitAdvance();
        }

        private void leave() {
            System.out.printf("%s 离开%n", name);
            //等待
            phaser.arriveAndAwaitAdvance();
        }

        private void hug() {
            if (name.equals("新郎") || name.equals("新娘")) {
                System.out.printf("%s 洞房!%n", name);
                phaser.arriveAndAwaitAdvance();
            } else {
                phaser.arriveAndDeregister();
            }
        }

        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hug();
        }
    }
}

class MarryPhaser extends Phaser{

    @Override
    protected boolean onAdvance(int phase, int registeredParties) {
        switch (phase) {
            //阶段0
            case 0:
                System.out.println("所有人到齐了 " + registeredParties);
                System.out.printf("\r\n");
                return false;
            //阶段1
            case 1:
                System.out.println("所有人吃完了"+registeredParties);
                System.out.printf("\r\n");
                return false;
            //阶段2
            case 2:
                System.out.println("所有人离开了"+registeredParties);
                System.out.printf("\r\n");
                return false;
            //阶段3
            case 3:
                System.out.println("婚礼结束!新郎新娘抱抱!"+registeredParties);
                System.out.printf("\r\n");
                //phaser是否需要结束，返回true时结束
                return true;
            default:
                return true;
        }
    }
}


